<?php
declare (strict_types = 1);
namespace app\admin\model;
use app\admin\model\AdminMenuApi as AdminMenuApiModel;
/**
 * 超管菜单接口列表模型
 */
class AdminApi extends BaseModel
{
	
	// 定义表名
    protected $name = 'admin_api';

    // 定义主键
    protected $pk = 'admin_api_id';

    // 追加字段
    // protected $append = [''];

    /**
     * 获取指定角色的所有菜单id
     * @param array $menuIds 菜单ID集
     * @return array
     */
    public static function getApiUrls(array $adminApiIds)
    {
        return (new self)->where('admin_api_id', 'in', $adminApiIds)->column('url');
    }
    
    /**
     * [getList 获取菜单树]
     * Author：上官钧墨
     * @return [type] [description]
     */
    public function getList()
    {
        $hidden = ['create_time','update_time'];
        $all = $this->where([])->hidden($hidden)->select();
        $list = $this->children($all);
        return $list;
    }
    /**
     * [children 生成菜单树]
     * Author：上官钧墨
     * @param  array  $all [所有数据]
     * @param  integer $pid [上级admin_menu_id]
     */
    private function children($all,$pid = 0){
        $list = [];
        foreach ($all as $v) {
            if ($v['pid'] == $pid) {
                $item = $this->children($all,$v['admin_api_id']);
                !empty($item) && $v['children'] = $item;
                $list[] = $v;
                unset($item);
            }
        }
        return $list;
    }
    /**
     * [addApi 新增]
     * Author：上官钧墨
     * @param [type] $data [description]
     */
    public function addApi($data=[])
    {
        $data['create_time'] = time();
        $data['update_time'] = time();
        return $this->insert($data);
    }
    /**
     * [editApi 编辑]
     * Author：上官钧墨
     * @param  [type] $data [更新数据]
     */
    public function editApi(array $data=[])
    {
        $data['update_time'] = time();
        return $this->save($data);
    }
    /**
     * [delApi 删除APi接口]
     * Author：上官钧墨
     */
    public function delApi()
    {
        $menuApiModel = new AdminMenuApiModel;
        $detail = $menuApiModel->where(['admin_api_id'=>$this->admin_api_id])->select();
        if (count($detail)>0) {
            $this->error = '删除失败，该Api接口已被分配到菜单，请先取消分配';
            return false;
        }
        $find = $this->detail(['pid'=>$this->admin_api_id]);
        if ($find) {
            $this->error = '删除失败，该记录下有关联Api接口';
            return false;
        }
        return $this->delete();
    }

    /**
     * [detail 获取详情]
     * Author：上官钧墨
     * @param  [type] $where [条件]
     */
    public function detail($where=[], $with = [],$hidden = [])
    {
        is_array($where) ? $filter = $where : $filter[$this->pk] = (int)$where;
        return $this->get($filter, $with,$hidden);
    }
}